<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;

class ContentResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $result = [
            'id' => $this->id,
            'mobile' => $this->mobile,
            'title' => $this->title,
            'type' => $this->type,
            'type_str' => $this->type_str,
            'descrition' => $this->descrition,
            'images' => collect($this->images)->map(function($img) {
                if (strpos($img, 'storage') !== false) {
                    return $img;
                }
                return Storage::url($img);
            }),
            'tags' => $this->tags,
            'stars' => $this->stars,
            'address' => $this->address,
            'longitude' => $this->longitude > 0 ? $this->longitude : 0,
            'latitude' => $this->latitude > 0 ? $this->latitude : 0,
            'status' => $this->status,
            'status_str' => $this->status_str,
            'created_at' => $this->refresh_at,
            'is_charge' => $this->is_charge,
            'is_charge_str' => $this->is_charge_str,

            'is_owner' => $this->is_owner,
            'is_collected' => $this->is_collected,
            'is_buy' => $this->is_buy,
            // 返回被删除原因
            'deleted_reason' => $this->when($this->status == -1, function() {
                return $this->data['delete_reason'] ?? '';
            }),
            // 返回职位
            'position' => $this->when(!empty($this->position), function() {
                return [
                    'id' => $this->position->id,
                    'name' => $this->position->name,
                ];
            }),
        ];

        return $result;
    }
}
